package com.hg.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Jdk动态代理
 * created by skh on 2019/9/7
 */
public class JdkProxy implements InvocationHandler {

	private Object realTarget;

	public JdkProxy(Object realTarget){
		this.realTarget = realTarget;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		before();
		Object result = method.invoke(realTarget, args);
		after();
		return result;
	}

	public Object getProxy() {
		return Proxy.newProxyInstance(realTarget.getClass().getClassLoader(), realTarget.getClass().getInterfaces(), this);
	}

	private void before() {
		System.out.println("前置增强");
	}

	private void after() {
		System.out.println("后置增强");
	}

	public static void main(String[] args) {
		JdkProxy jdkProxy = new JdkProxy(new HelloImpl());
		Hello proxy = (Hello)jdkProxy.getProxy();
		proxy.sayHello();
	}
}
